package com.config.exception;


import com.common.ErrorCode;
import com.common.UIResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.orm.jpa.JpaSystemException;
import org.springframework.web.bind.annotation.*;

import java.io.UnsupportedEncodingException;

@ControllerAdvice
@Slf4j
public class GlobalDefultExceptionHandler {


  private final Log logger = LogFactory.getLog(getClass());


  @ExceptionHandler(value = {GlobalException.class,Exception.class,RuntimeException.class})
  @ResponseBody
  public UIResult handleCustomException(Exception e) {
    logger.error(e);
    e.printStackTrace();

    String message = e.getMessage();

    if (e instanceof UnsupportedEncodingException) {
      message = "生成用户秘钥出现错误：" + e.getMessage();
    }  else if (e instanceof JpaSystemException) {
      message = "后台数据处理出现异常！";
    } else if (e instanceof GlobalException) {
      GlobalException exception = (GlobalException) e;
      return UIResult.Error(exception);
    }
    return UIResult.Error(ErrorCode.SERVER_ERROR).setMsg(message);
  }

}
